import { useLayoutEffect, Suspense } from 'react'
import type { FC } from 'react'
import { Form, Input, Button, Select } from 'antd'
import type { FormProps } from 'antd'
import { useLoaderData, Await } from 'react-router-dom'
import useArtAddStore, { setCurrent, Move, setBaseForm, selectBaseForm } from '@/store/art-add-store.ts'

const ArticleBase: FC = () => {
  const loaderData = useLoaderData() as { cates: BaseResponse<CateItem[]> }
  const [formRef] = Form.useForm()
  const baseForm = useArtAddStore(selectBaseForm)

  useLayoutEffect(() => {
    formRef.setFieldsValue(baseForm)
  }, [formRef, baseForm])

  const onFinish = () => {
    setCurrent(Move.next)
  }

  const handleValuesChange: FormProps['onValuesChange'] = (newValues) => {
    setBaseForm(newValues)
  }

  return (
    <>
      <Form form={formRef} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} style={{ maxWidth: 600 }} onFinish={onFinish} onValuesChange={handleValuesChange} autoComplete="off">
        <Form.Item label="文章标题" name="title" rules={[{ required: true, message: '请填写文章标题!' }]}>
          <Input maxLength={30} placeholder="请填写文章标题" allowClear showCount />
        </Form.Item>

        <Suspense
          fallback={
            <Form.Item label="文章分类" rules={[{ required: true, message: '请选择文章分类!' }]}>
              <Select placeholder="请选择文章分类" loading={true} />
            </Form.Item>
          }
        >
          <Await resolve={loaderData.cates}>
            {(cates: BaseResponse<CateItem[]>) => {
              return (
                <Form.Item label="文章分类" name="cate_id" rules={[{ required: true, message: '请选择文章分类!' }]}>
                  <Select placeholder="请选择文章分类" allowClear options={cates.data} fieldNames={{ label: 'cate_name', value: 'id' }} />
                </Form.Item>
              )
            }}
          </Await>
        </Suspense>

        <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
          <Button type="primary" htmlType="submit">
            下一步
          </Button>
        </Form.Item>
      </Form>
    </>
  )
}

export default ArticleBase
